|
|
|
|
|
|
|
The final Boolean operation we'll concern ourselves with is the XOR, or "exclusive-or" operator. It's a rather peculiar operator, and beginners usually have a hard time seeing what it might be good for. Let's take a hypothetical example where a variable has three flag bits. The bits have constants BIT0, BIT1, and BIT2, defined earlier in this tutorial. |
|
|
|
|
|
|
|
|
Now let's try something a little bit different. What happens if you use the XOR operator using the BIT1 mask? |
|
|
|
|
|
|
|
|
6 Xor BIT1 -> 0110 Xor 0010 -> 0100 = &H4 |
|
|
|
|
|
|
|
|
The XOR operator cleared the bit in one operation. What happens if you perform the same operator again on the result? |
|
|
|
|
|
|
|
|
4 Xor BIT1 -> 0100 Xor 0010 -> 0110-> &H6 |
|
|
|
|
|
|
|
|
To set a bit, use the OR operator with a bit mask. |
|
|
|
|
|
|
|
|
To check a bit, use the AND operator with a bit mask. |
|
|
|
|
|
|
|
|
To clear a bit, use the AND operator with the inverse bit mask (the bit mask after the NOT operator has been applied). |
|
|
|
|
|
|
|
|
To toggle a bit, use the XOR operator. |
|
|
|
|
|
|
|
|
The most important place where you'll toggle bits will be with graphic operations. The XOR operator is unique in that, if you apply it to a variable then apply it again to the result, you'll get the original value. If you use the XOR operator in image operations, you can apply it once to modify an image (say, by drawing a line or combining a second image with the first), then again to restore the previous image. Sprites, animation, and cursors frequently use the XOR operator in this way. |
|
|
|
|
|
|
|
|
The XORLine.vbp sample program on the CD-ROM for this book illustrates this. To test it for yourself, create a form with the following properties: |
|
|
|
|
| BorderStyle | 3 - Fixed Dialog | | DrawMode | 7 - Xor Pen | | ForeColor | &H00FFFFFF& (white pen) |
|
|
|